﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace UPos.Core.DataDriver
{
    class DbSQLServer : IDisposable
    {
        public static string DefaultConnectionString { get; set; }

        static DbSQLServer()
        {
            if (string.IsNullOrWhiteSpace(DefaultConnectionString))
            {
                var setting = ConfigurationManager.ConnectionStrings["sqlserver"];
                if (setting == null)
                    throw new ConfigurationErrorsException("ConnectionString 配置节，必须至少包含一个名为 sqlserver 的项");
                DefaultConnectionString = setting.Decode();
            }
        }

        SqlConnection CoreConn { get; set; }

        public DbSQLServer()
        {
            CoreConn = new SqlConnection(DefaultConnectionString);
            CoreConn.Open();
        }

        internal object ExecuteScalar(string sql, params SqlParameter[] sqlParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(sqlParameters);
                return cmd.ExecuteScalar();
            }
        }

        internal SqlDataReader ExecuteReader(string sql, params SqlParameter[] sqlParameters)
        {
            using (var cmd = CoreConn.CreateCommand())
            {
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(sqlParameters);
                return cmd.ExecuteReader();
            }
        }

        internal DataTable GetTableSchema(string tableName)
        {
            using (var adapter = new SqlDataAdapter("select * from " + tableName, CoreConn))
            {
                var t = new DataTable();
                adapter.FillSchema(t, SchemaType.Mapped);
                return t;
            }
        }

        public void Dispose()
        {
            CoreConn.Dispose();
        }
    }
}
